<template>
  <div>
     <a-upload
        name="file"
        :multiple="false"
        :headers="this.token"
        :fileList="fileListData"
        :beforeUpload="beforeUpload"
        listType="picture-card"
        accept=".png,.jpg,jpeg"
        :action="uploadService"
        :data="{uploadPath:'/shuili/jbtsTwo','isRename':true,'appId':true}"
        @preview="handlePreview"
        @change="handleChange"
      >
        <div v-if="fileListData.length < 6">
          <a-icon type="plus" />
          <div class="ant-upload-text diy-ant-upload-text">点击添加图片</div>
          <div class="ant-upload-text diy-ant-upload-text">最多添加6张图片</div>
        </div>
      </a-upload>
      <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
  </div>
</template>

<script>
  import { mapState, mapActions } from 'vuex'
  import { getToken } from '@/utils/token'
  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = error => reject(error)
    })
  }
  export default {
    props: ['imgURL'],
    data() {
      return {
        token: { token: getToken() },
        uploadService:  '/api/file/upload.do', //上传服务器地址
        uploadPath: this.$globalConfig.uploadPath + '/file/',  // 图片路径服务器地址
        fileList: [],
        fileListData: [],
        previewVisible: false,
        previewImage: '',
      }
    },
    methods: {
      // 父组件调用
      // this.fileList = this.$refs.UploadImages.fileList
      // if(this.fileList.length>0) {
      //   formData.headImg = this.fileList.map((obj,index)=>{
      //     return obj.response.data[0];
      //   }).join(',')
      // }
      beforeUpload(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
          this.$message.error('只能上传jpg/png格式图片')
        }
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('文件超过2M了')
        }
        return isJpgOrPng && isLt2M
      },
      async handlePreview(file) {
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj)
        }
        this.previewImage = file.url || file.preview
        this.previewVisible = true
      },
      handleChange({ file, fileList }) {
        if (file.status !=='removed' && file.response!==undefined &&  typeof file.response!=='string') {
          this.$message.error('上传失败，检查服务是否正常或者重新上传')
          return
        }
        if (file.status === 'removed') {
          this.fileListData = fileList
          this.fileList = this.fileListMap(this.fileListData)
        }
        if (file.status === 'uploading' && (file.size / 1024 / 1024 < 2)) {
          this.fileListData = fileList
        }
        if (file.status === 'done' && typeof file.response==='string') {
          this.fileList = this.fileListMap(this.fileListData)
        }
      },
      fileListMap(fileListData) {
        let datas = []
        for(let item of fileListData) {
          let items = {}
          if(item.response ) {
             items = Object.assign(
                {response: item.response},
                { url: item.response },
                { name: item.name },
                { path: item.response },
                { size: item.size },
                { percentage: item.percent },
                { uid: item.uid }
              );
            datas.push(items)
          }
        }
        this.$emit("getImages", datas)
        return datas
      },
      handleCancel() {
        this.previewVisible = false
      },
    },
  }
</script>

<style scoped lang="less">
.diy-ant-upload-text{
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #999999;
}
.ant-upload-picture-card-wrapper {
    zoom: 1;
    display: flex;
    width: 100%;
}
.anticon {
    display: inline-block;
    color: #cccccc;
    font-style: normal;
    font-size: 24px;
    right: 0;
    text-align: center;
    text-transform: none;
    vertical-align: -0.125em;
    text-rendering: optimizeLegibility;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}
</style>
